package com.tang.hawkmusic.activity.local;

import android.app.Application;
import android.database.Cursor;
import android.provider.MediaStore;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.AndroidViewModel;

import com.tang.hawkmusic.bean.music.LocalMusic;
import com.tang.hawkmusic.fragment.LocalMusicFragment;
import com.tang.hawkmusic.fragment.LocalMvFragment;
import com.tang.hawkmusic.fragment.LocalVoiceFragment;

import java.util.ArrayList;

public class LocalViewModel extends AndroidViewModel {
    private ArrayList<Fragment> fragments;
    private ArrayList<LocalMusic> musics;
    public LocalViewModel(@NonNull Application application) {
        super(application);
    }
    public void initFragments(){
        fragments=new ArrayList<>();
        LocalMusicFragment localMusicFragment=new LocalMusicFragment(getApplication());
        LocalVoiceFragment localVoiceFragment=new LocalVoiceFragment(getApplication());
        LocalMvFragment localMvFragment=new LocalMvFragment(getApplication());
        fragments.add(localMusicFragment);
        fragments.add(localVoiceFragment);
        fragments.add(localMvFragment);
    }

    public ArrayList<Fragment> getFragments() {
        return fragments;
    }

    public void initMusicList(){
        musics=new ArrayList<>();
        Cursor cursor=getApplication().getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
                ,null,null,null, MediaStore.Audio.AudioColumns.IS_MUSIC);
        if (cursor!=null){
            while (cursor.moveToNext()){
                LocalMusic music=new LocalMusic();
                music.setName(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME)));
                music.setSinger(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST)));
                music.setPath(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA)));
                music.setDuration(cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION)));
                music.setSize(cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.SIZE)));

                if (music.getName().contains("-")){
                    String[] str=music.getName().split("-");
                    music.setSinger(str[1]);
                    music.setName(str[0]);
                }
                if (!music.getSinger().equals("<unknown>")&&!music.getName().contains("m4a"))
                    musics.add(music);
                //Log.d("TAG", "initMusicList: "+music.getPath());

            }
            cursor.close();
        }

    }

    public ArrayList<LocalMusic> getMusics() {
        return musics;
    }
}
